import { post, apiPaths } from '../../utils/request.js'

Page({
  data: {
    userInfo: {},
    currentDate: '',
    projectCount: 0,
    taskCount: 0,
    completedTaskCount: 0,
    inProgressProjects: [],
    recentTasks: []
  },

  onLoad() {
    this.loadUserInfo()
    this.setCurrentDate()
    this.loadDashboardData()
  },

  loadUserInfo() {
    const userInfo = wx.getStorageSync('userInfo') || {}
    this.setData({
      userInfo: userInfo
    })
  },

  setCurrentDate() {
    const now = new Date()
    const year = now.getFullYear()
    const month = now.getMonth() + 1
    const day = now.getDate()
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const weekday = weekdays[now.getDay()]
    
    this.setData({
      currentDate: `${year}年${month}月${day}日 ${weekday}`
    })
  },

  loadDashboardData() {
    // 并行请求多个接口获取首页数据
    Promise.all([
      post(apiPaths.getStatistics),
      post(apiPaths.getProjects),
      post(apiPaths.getTasks)
    ]).then(responses => {
      const [statsRes, projectsRes, tasksRes] = responses
      
      // 处理统计概览数据
      if (statsRes.code === 200) {
        const stats = statsRes.data
        this.setData({
          projectCount: stats.projects.total,
          taskCount: stats.tasks.total,
          completedTaskCount: stats.tasks.completed
        })
      } else {
        wx.showToast({
          title: statsRes.message || '获取统计信息失败',
          icon: 'none'
        })
      }
      
      // 处理进行中的项目数据
      if (projectsRes.code === 200) {
        const projects = (projectsRes.data || [])
          .filter(project => project.status === '进行中')
          .slice(0, 3) // 只显示前3个
        
        this.setData({
          inProgressProjects: projects
        })
      } else {
        wx.showToast({
          title: projectsRes.message || '获取项目信息失败',
          icon: 'none'
        })
      }
      
      // 处理最近的任务数据
      if (tasksRes.code === 200) {
        const tasks = (tasksRes.data || [])
          .slice(0, 3) // 只显示前3个
          .map(task => {
            return {
              ...task,
              statusClass: this.getStatusClass(task.status),
              priorityClass: this.getPriorityClass(task.priority)
            }
          })
        
        this.setData({
          recentTasks: tasks
        })
      } else {
        wx.showToast({
          title: tasksRes.message || '获取任务信息失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.message || '获取首页数据失败',
        icon: 'none'
      })
    })
  },
  
  getStatusClass(status) {
    switch (status) {
      case '已完成':
        return 'completed'
      case '处理中':
        return 'in-progress'
      case '待测试':
        return 'pending'
      default:
        return 'pending'
    }
  },
  
  getPriorityClass(priority) {
    switch (priority) {
      case '紧急':
        return 'urgent'
      case '高':
        return 'high'
      case '中':
        return 'medium'
      case '低':
        return 'low'
      default:
        return 'medium'
    }
  },

  onNavigateToProjects() {
    wx.navigateTo({
      url: '/pages/projects/projects'
    })
  },

  onNavigateToTasks() {
    wx.navigateTo({
      url: '/pages/tasks/tasks'
    })
  },

  onNavigateToStatistics() {
    wx.navigateTo({
      url: '/pages/statistics/statistics'
    })
  },

  onNavigateToTeam() {
    wx.navigateTo({
      url: '/pages/team/team'
    })
  },

  onProjectTap(e) {
    const projectId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/projectDetail/projectDetail?id=${projectId}`
    })
  },

  onTaskTap(e) {
    const taskId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/taskDetail/taskDetail?id=${taskId}`
    })
  }
})